package com.hxtec.polaris.service.impl;

import com.hxtec.polaris.commons.api.vo.Result;
import com.hxtec.polaris.commons.constant.Code;
import com.hxtec.polaris.commons.constant.GlobalVar;
import com.hxtec.polaris.commons.constant.Log;
import com.hxtec.polaris.commons.constant.Msg;
import com.hxtec.polaris.commons.dto.ExpressDto;
import com.hxtec.polaris.commons.dto.OmsOrderDeliveryParam;
import com.hxtec.polaris.commons.dto.Page;
import com.hxtec.polaris.commons.exception.MyException;
import com.hxtec.polaris.commons.utils.MyExpress;
import com.hxtec.polaris.entity.ShopExpressCompany;
import com.hxtec.polaris.entity.ShopLogisticCompany;
import com.hxtec.polaris.entity.ShopOrder;
import com.hxtec.polaris.entity.ShopOrderHistory;
import com.hxtec.polaris.mapper.ShopExpressCompanyMapper;
import com.hxtec.polaris.mapper.ShopLogisticCompanyMapper;
import com.hxtec.polaris.mapper.ShopOrderHistoryMapper;
import com.hxtec.polaris.mapper.ShopOrderMapper;
import com.hxtec.polaris.service.OrderManagerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Describtion OMS 相关
 * @Author yonyong
 * @Date 2019/12/23 14:39
 * @Version 1.0.0
 **/
@Service
@Transactional
public class OrderManagerServiceImpl implements OrderManagerService {

    @Resource
    ShopOrderMapper shopOrderMapper;

    @Resource
    ShopOrderHistoryMapper shopOrderHistoryMapper;

    @Resource
    ShopLogisticCompanyMapper shopLogisticCompanyMapper;

    @Resource
    ShopExpressCompanyMapper shopExpressCompanyMapper;

    @Override
    public Object list(int pageNum, int pageSize, String orderSn, String receiverKeyword, String status, String updateTime) {
        try {
            return doList(pageNum,pageSize,orderSn,receiverKeyword,status,updateTime);
        }catch (Exception e){
            String params = "pageNum="+pageNum + ";pageSize=" + pageSize + ";orderSn=" + orderSn + ";receiverKeyword=" + receiverKeyword
                    + ";status=" + status + ";createTime=" + updateTime;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.QUERY,"OrderManagerServiceImpl","list",params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    @Override
    public Map<String, Object> getDetail(int id) {
        try {
            return doGetDetail(id);
        }catch (Exception e){
            String params = "id="+id;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.QUERY,"OrderManagerServiceImpl","getDetail",params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    @Override
    public String closeOrder(String[] ids, String note) {
        try {
            return doCloseOrder(ids,note);
        }catch (Exception e){
            String params = "ids="+ Arrays.toString(ids)+";note="+note;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.UPDATE,"OrderManagerServiceImpl","closeOrder",params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        try {
            return doDelivery(deliveryParamList);
        }catch (Exception e){
            String params = "deliveryParamList="+ deliveryParamList;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.UPDATE,"OrderManagerServiceImpl","delivery",params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    @Override
    public int receiverInfo(int id, String name, String phone, String postcode, String detail) {
        try {
            return doReceiverInfo(id,name,phone,postcode,detail);
        }catch (Exception e){
            String params = "id="+ id+";name="+name+";phone="+phone+";postcode="+postcode+";detail="+detail;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.UPDATE,"OrderManagerServiceImpl","receiverInfo",params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    @Override
    public List<ExpressDto> getExpressInfo(String company, String code) {
        try{
            ShopLogisticCompany shopLogisticCompany = shopLogisticCompanyMapper.selectByName(company);
            return MyExpress.getExpressInfo(code,company,shopLogisticCompany.getCode());
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL));
        }
    }

    @Override
    public void addOrderRecord(int orderId,String operator,int order_state,String note) {
        ShopOrderHistory shopOrderHistory = new ShopOrderHistory();
        shopOrderHistory.setOrderId(orderId);
        shopOrderHistory.setOperator(operator);
        shopOrderHistory.setOperateTime(new Date());
        if(StringUtils.isNotBlank(note)){
            shopOrderHistory.setNote(note);
        }
        shopOrderHistory.setOrderState(String.valueOf(order_state));
        shopOrderHistoryMapper.insertDynamic(shopOrderHistory);
    }

    @Override
    public List<ShopLogisticCompany> getLogistic() {
        try{
            return shopLogisticCompanyMapper.selectAll();
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL));
        }
    }

    @Override
    public int updateLogistic(ShopLogisticCompany shopLogisticCompany) {
        //校验快递公司是否合法
        String code = MyExpress.getCompanyInfo(shopLogisticCompany.getName());
        if (StringUtils.isBlank(code)){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMPANY_CODE_NULL));
        }
        try{
            shopLogisticCompany.setCode(code);
            return shopLogisticCompanyMapper.updateDynamic(shopLogisticCompany);
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL));
        }
    }

    @Override
    public int addLogistic(ShopLogisticCompany shopLogisticCompany) {
        //校验快递公司是否合法
        String code = MyExpress.getCompanyInfo(shopLogisticCompany.getName());
        if (StringUtils.isBlank(code)){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMPANY_CODE_NULL));
        }
        try{
            shopLogisticCompany.setCode(code);
            return shopLogisticCompanyMapper.insertDynamic(shopLogisticCompany);
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL));
        }
    }

    @Override
    public int deleteLogistic(ShopLogisticCompany shopLogisticCompany) {
        try{
            return shopLogisticCompanyMapper.delete(shopLogisticCompany.getId());
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL));
        }
    }

    @Override
    public List<ShopExpressCompany> selectLogistic(String name) {
        try{
            return shopExpressCompanyMapper.getList(name);
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL));
        }
    }

    /**
     * 执行修改收货人信息
     * @param id
     * @param name
     * @param phone
     * @param postcode
     * @param detail
     * @return
     */
    private int doReceiverInfo(int id, String name, String phone, String postcode, String detail) {
        int count = shopOrderMapper.doReceiverInfo(id,name,phone,postcode,detail);
        ShopOrder shopOrder = shopOrderMapper.getOrderById(id);
        addOrderRecord(id, GlobalVar.OPERATER_ADMIN,shopOrder.getState(),"后台管理员更新订单收货人信息");
        return count;
    }

    /**
     * 执行批量发货
     * @param deliveryParamList
     * @return
     */
    private int doDelivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = shopOrderMapper.delivery(deliveryParamList);
        for (OmsOrderDeliveryParam item:deliveryParamList) {
            addOrderRecord(item.getOrderId().intValue(), GlobalVar.OPERATER_ADMIN,GlobalVar.ORDER_RECIIVEING,"后台管理员发货");
        }
        return count;
    }

    /**
     * 执行关闭订单
     * @param ids
     * @param note
     * @return
     */
    private String doCloseOrder(String[] ids, String note) {
        shopOrderMapper.doCloseOrder(ids,new Date());
        for (String id:ids) {
            ShopOrder shopOrder = shopOrderMapper.getOrderById(Integer.valueOf(id));
            addOrderRecord(Integer.valueOf(id), GlobalVar.OPERATER_ADMIN,shopOrder.getState(),note);
        }
        return null;
    }

    /**
     * 执行获取订单详情方法
     * @param id
     * @return
     */
    private Map<String,Object> doGetDetail(int id) {
        Map<String,Object> map = shopOrderMapper.doGetDetail(id);
        List<Map<String,Object>> itemList = shopOrderMapper.getOrderItemsByOneOrder(null,id);
        map.put("goods",itemList);
        List<ShopOrderHistory> shopOrderHistoryList = shopOrderHistoryMapper.selectByOrderId(id);
        map.put("history",shopOrderHistoryList);
        return map;
    }

    /**
     * 执行初始化获取订单信息
     * @param pageNum
     * @param pageSize
     * @param orderSn
     * @param receiverKeyword
     * @param status
     * @param updateTime
     * @return
     */
    private Result doList(int pageNum, int pageSize, String orderSn, String receiverKeyword, String status, String updateTime) {
        //分页信息
        int count = shopOrderMapper.getOrderCountMng(orderSn,receiverKeyword,status,updateTime);
        Page page = new Page(count,pageNum,pageSize);

        //数据信息
        //分页查出订单信息
        List<Map<String,Object>> list = shopOrderMapper.getOrderMng((pageNum-1)*pageSize,pageSize,orderSn,receiverKeyword,status,updateTime);
        return Result.ok(page,list);
    }
}
